package state

import (
	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/types"
	pbcom "hundsun.com/hsl/hschain/protos/common"
	"hundsun.com/hsl/hschain/store/db"
)

const (
	// StateInfo 最新的状态信息
	StateInfo = "ns.state.info"
)

// InfoDB 最新状态信息读取对象
type InfoDB struct {
	get db.DatabaseGet
}

// NewInfoDB new InfoDB
func NewInfoDB(get db.DatabaseGet) *InfoDB {
	return &InfoDB{get: get}
}

// GetStateInfo get StateInfo
func (st *InfoDB) GetStateInfo() (*pbcom.StateInfo, error) {
	if st.get == nil {
		return nil, types.ErrNotFound
	}
	v, err := st.get.Get([]byte(StateInfo))
	if err != nil {
		return nil, err
	}
	info := &pbcom.StateInfo{}
	err = proto.Unmarshal(v, info)
	if err != nil {
		return nil, err
	}
	return info, nil
}

// InfoKV StateInfo to KV
func InfoKV(info *pbcom.StateInfo) (*pbcom.KeyValue, error) {
	v, err := proto.Marshal(info)
	if err != nil {
		return nil, err
	}
	return &pbcom.KeyValue{Key: []byte(StateInfo), Value: v}, nil
}
